<style lang="less">
  @import '../styles/common.less';
  @import '../tables/components/table.less';
</style>

<template>
  <div>
    <Row :gutter="10">
      <Card>
        <div class="table-head">
          <div class="left">
            <Select v-model="typeSelectid" :transfer="true" @on-change="onChangeTypeSelect">
              <Option v-for="item in typeSelect" :value="item.id" :key="item.id">{{ item.title }}</Option>
            </Select>
          </div>
          <Button type="primary" class="Button" @click="ExportData()">导出数据</Button>
          <Button type="primary" class="Button" @click="remove()">删除</Button>
          <Button type="primary" class="Button" @click="add()">添加</Button>
        </div>
        <Row class="margin-top-10">
          <Table stripe border :columns="columns" :data="data" @on-row-click="onRowData"
                 @on-selection-change="selectionChange"></Table>
        </Row>
        <div style="margin: 10px;overflow: hidden;height: 36px;">
          <div style="float: right;">
            <Page :total="total" :current="page" @on-change="changePage" show-elevator></Page>
          </div>
        </div>
      </Card>
      <!--详情-->
      <Drawer :closable="false" :width="DrawerWidth" v-model="showCurrentTableData" class="Drawer-body">
        <div class="Drawer_pStyle">
          <span></span>
          <span class="del" @click="asyncOK"><Icon type="md-close"/></span>
        </div>
        <div class="body">
          <Form label-position="top">
            <FormItem label="标题">
              <div class="dataDetail-div" v-text="dataDetail.title"></div>
            </FormItem>
            <FormItem label="类别" v-if="dataDetail.type">
              <div class="dataDetail-div" v-text="dataDetail.type.name"></div>
            </FormItem>
            <FormItem label="标签">
              <div class="dataDetail-div" v-text="dataDetail.tag"></div>
            </FormItem>
            <FormItem label="部门" v-if="dataDetail.department">
              <div class="dataDetail-div" v-text="dataDetail.department.name"></div>
            </FormItem>
            <FormItem label="创建时间">
              <div class="dataDetail-div" v-text="dataDetail.create_time"></div>
            </FormItem>
            <FormItem label="状态" v-if="dataDetail.status">
              <div class="dataDetail-div" v-text="dataDetail.status.title"></div>
            </FormItem>
            <FormItem label="可见范围">
              <div class="dataDetail-div" v-text="show_users"></div>
            </FormItem>
            <FormItem label="自动化工作流">
              <div class="dataDetail-div" v-text="dataDetail.is_workflow==true ? '是' : '否'"></div>
            </FormItem>
            <FormItem label="自动化消息">
              <div class="dataDetail-div" v-text="dataDetail.is_notify==true ? '是' : '否'"></div>
            </FormItem>
            <FormItem label="内容" v-if="dataDetail.content">
              <div class="dataDetail-div ck-editor-content" v-html="dataDetail.content"></div>
            </FormItem>

          </Form>
        </div>
        <div class="footer" :style="{width: DrawerWidth - 32 + 'px'}">
          <Button type="text" @click="asyncOK">取消</Button>
          <Button type="primary" :loading="saveLoading" @click="fabu()"
                  v-if="dataDetail.status && dataDetail.status.id == 3">发布
          </Button>
        </div>
      </Drawer>
      <!--编辑-->
      <Drawer :closable="false" :width="WindowWidth" v-model="addCurrentTableData" class="Drawer-body">
        <div class="Drawer_pStyle">
          <span>编辑</span>
          <span class="del" @click="hideAddModal"><Icon type="md-close"/></span>
        </div>
        <div class="body">
          <table class="add-table" border="0" cellpadding="0" cellspacing="0">
            <tr>
              <td class="left paddingTop22" valign="top" align="right">
                <Form label-position="top" class="from-content">
                  <FormItem label="">
                    <Input v-model="addData.title" placeholder="请输入标题"></Input>
                  </FormItem>
                  <FormItem label="">
                    <!--<textarea name="content" id="content"></textarea>-->
                    <div id="content" class="ck-editor-content" :style="{minHeight: WindowHeight - 252 + 'px'}"></div>
                    <!--<div id="toolbar-container"></div>
                    <div id="editor" class="editor-content"></div>-->
                  </FormItem>
                </Form>
              </td>
              <td class="right" valign="top" :style="{width: WindowWidth > 1440 ? WindowWidth*0.3 + 'px' : '288px'}">
                <Form label-position="top">
                  <FormItem label="类别">
                    <Select v-model="addData.type" :transfer="true" style="width:100%;">
                      <Option v-for="item in typeArr" :value="item.id" :key="item.id">{{ item.title }}</Option>
                    </Select>
                  </FormItem>
                  <FormItem label="标签">
                    <Input v-model="addData.tag" placeholder="标签"></Input>
                  </FormItem>
                  <FormItem label="审批人">
                    <Select v-model="addData.approvers" :transfer="true" style="width:100%;">
                      <Option v-for="item in approversArr" :value="item.id" :key="item.id">{{ item.name }}</Option>
                    </Select>
                  </FormItem>
                  <FormItem label="自动化工作流">
                    <i-switch v-model="addData.is_workflow" size="large">
                      <span slot="open">是</span>
                      <span slot="close">否</span>
                    </i-switch>
                  </FormItem>
                  <FormItem label="选择日期" v-if="addData.is_workflow == true">
                    <DatePicker type="daterange"
                                format="yyyy-MM-dd"
                                :confirm="true"
                                :transfer="true"
                                :editable="false"
                                split-panels
                                placement="bottom-start"
                                placeholder="请选择日期"
                                v-model="addData.DatePickerValue"
                                style="width: 100%;"></DatePicker>
                  </FormItem>
                  <FormItem label="自动化消息">
                    <i-switch v-model="addData.is_notify" size="large">
                      <span slot="open">是</span>
                      <span slot="close">否</span>
                    </i-switch>
                  </FormItem>
                  <FormItem label="可见范围">
                    <div class="dataDetail-div">
                      <Tree ref="user_tree" :data="TreeData" show-checkbox multiple></Tree>
                    </div>
                  </FormItem>
                </Form>
              </td>
            </tr>
          </table>
        </div>
        <div class="footer" :style="{width: WindowWidth - 32 + 'px'}">
          <Button type="text" @click="hideAddModal">取消</Button>
          <Button type="primary" :loading="saveLoading" @click="save()">确定</Button>
        </div>
      </Drawer>
    </Row>
  </div>
</template>

<script>
  import Cookies from 'js-cookie';
  import Util from '../../libs/util';
  import Utils from '../../libs/mod.utils';
  import String from '../../libs/mod.string';
  import Modal from '../../libs/mod.Modal';
  import Ckeditor from '../../libs/mod.ckeditor';
  export default {
    components: {},
    data () {
      return {
        total: 0,
        page: 1,
        size: 10,
        id: '',
        show_users: '',
        searchConName: '',
        searchConTel: '',
        showCurrentTableData: false,
        loading: true,
        showCurrentColumns: [],
        editInlineAndCellData: [],
        columns: [
          {
            type: 'selection',
            width: 60,
            align: 'center'
          },
          {
            key: 'title',
            title: '标题',
          },
          {
            key: 'type',
            title: '类别',
            render: (h, params) => {
              return h('div', [
                h('span', params.row.type.name)
              ]);
            }
          },
          {
            key: 'department',
            title: '部门',
            render: (h, params) => {
              return h('div', [
                h('span', params.row.department.name)
              ]);
            }
          },
          {
            key: 'status',
            title: '状态',
            render: (h, params) => {
              return h('div', [
                h('span', params.row.status.title)
              ]);
            }
          },
          {
            key: 'create_time',
            title: '创建时间',
            width: 160
          },
          {
            title: 'Action',
            key: 'action',
            width: 150,
            align: 'center',
            render: (h, params) => {
              return h('div', [
                h('Button', {
                  props: {
                    type: 'primary',
                    size: 'small'
                  },
                  style: {
                    marginRight: '5px'
                  },
                  on: {
                    click: e => {
                      e.stopPropagation();
                      var data = params.row;
                      this.update(data, params.index);
                    }
                  }
                }, '修改')
              ]);
            }
          }
        ],
        data: [],
        dataDetail: {},
        initTable: [],
        addCurrentTableData: false,
        saveLoading: false,
        ajaxType: 'add',
        addData: {
          title: '',
          type: '',
          tag: '',
          approvers: '',
          is_notify: false,
          is_workflow: false,
          DatePickerValue: [],//['2018-06-06', '2018-07-07'],
          content: '',
        },
        selectionArr: [],
        approversArr: [],
        TreeData: [],
        checked_dep_arr: [],
        checked_users_arr: [],
        editor: null,
        DrawerWidth: Util.constant.DrawerWidth,// 抽屉的宽度
        WindowWidth: Util.constant.WindowWidth,// 窗口的宽度
        WindowHeight: Util.constant.WindowHeight,// 窗口的高度
        typeSelectid: 'all',
        typeSelect: [
          {
            id: 'all',
            title: '全部',
          },
        ],
        typeArr: [],
      };
    },
    created: function () {
      var _this = this;
      // 收藏夹跳转过来的
      var collection_list_str = sessionStorage.getItem('collection_list');
      if (collection_list_str && collection_list_str != '') {
        var collection_list_obj = Util.toJson(collection_list_str);
        var id = collection_list_obj.id || '';
        var type = collection_list_obj.type || '';
        sessionStorage.removeItem('collection_list');
      }
    },
    mounted () {
      this.getData();
      this.getApproversArr();
      this.getTypeArr();
    },
    methods: {
      onChangeTypeSelect: function (val) {
        var _this = this;
        _this.typeSelectid = val;
        _this.page = 1;
        _this.getData();
      },
      getData () {
        var _this = this;
        var data = {
          uid: Util.toJson(localStorage.getItem('userInfo')).id,
          page: _this.page,
          size: _this.size,
          tid: _this.typeSelectid == 'all' ? '' : _this.typeSelectid,
        };
        var params = {
          url: '/announcement/list',
          type: Util.method.get,
          data: data,
          success: _successFun
        };
        Util.ajax(_this, params);
        function _successFun(res) {
          if (res.result == 0) {
            var _data = res.data || [];
            _this.total = res.rows;
            _this.data = _data;
          } else {
            _this.$Message.error('查询信息失败!');
          }
        }
      },
      handleSearch () {
        var _this = this;
        _this.page = 1;
        var searchConName = _this.searchConName;
      },
      changePage (page) {
        var _this = this;
        console.log('page', page);
        _this.page = page;
        _this.getData();
      },
      onRowData: function (data, index) {
        var _this = this;
        _this.show(index, data);
      },
      show: function (index, data) {
        var _this = this;
        var id = data.id;
        _this.id = id;

        var data = {
          id: _this.id,
        };
        var params = {
          url: '/announcement/query',
          type: Util.method.get,
          data: data,
          success: _successFun
        };
        Util.ajax(_this, params);
        function _successFun(res) {
          if (res.result == 0) {
            var _data = res.data || [];
            var userArr = [];
            var departments = [];
            var dep = _data.assign_users.departments;
            if (dep instanceof Array) {
              departments = dep;
            } else {
              departments.push(dep);
            }
            var users = _data.assign_users.users;
            for (var k in departments) {
              if (!departments[k]) {
                continue;
              }
              var name = departments[k].name;
              userArr.push(name);
            }
            for (var k in users) {
              if (!users[k]) {
                continue;
              }
              var name = users[k].name;
              userArr.push(name);
            }
            _this.show_users = userArr.join(' ， ');
            _this.dataDetail = _data;
            _this.showCurrentTableData = true;
          } else {
            _this.$Message.error('查询信息失败!');
          }
        }
      },
      asyncOK: function () {
        var _this = this;
        _this.showCurrentTableData = false;
      },
      // 获取审批人
      getApproversArr: function () {
        var _this = this;
        var data = {};
        var params = {
          url: '/approval/leader',
          type: Util.method.get,
          data: data,
          success: _successFun
        };
        Util.ajax(_this, params);
        function _successFun(res) {
          if (res.result == 0) {
            var _data = res.data || [];
            _this.approversArr = _data.approvers;
          } else {
            _this.$Message.error('查询信息失败!');
          }
        }
      },
      // 获取类别
      getTypeArr: function () {
        var _this = this;
        var data = {};
        var params = {
          url: '/announcement/type/list',
          type: Util.method.get,
          data: data,
          success: _successFun
        };
        Util.ajax(_this, params);
        function _successFun(res) {
          if (res.result == 0) {
            var _data = res.data || [];
            _this.typeArr = _data;
            _this.typeSelect.push(..._data);
          } else {
            _this.$Message.error('查询类别信息失败!');
          }
        }
      },
      // 富文本
      initCkeditor () {
        var _this = this;
        Ckeditor.initCkeditor(_this, 'content', function (editor) {
          _this.editor = editor;
          _this.editor.setData(_this.addData.content);
        });
      },
      // 获取选人 树信息
      getTreeData: function () {
        var _this = this;
        var data = {
          uid: Util.toJson(localStorage.getItem('userInfo')).id,
          id: 1
        };
        var params = {
          url: '/department/query',
          type: Util.method.get,
          data: data,
          success: _successFun
        };
        Util.ajax(_this, params);
        function _successFun(res) {
          if (res.result == 0) {
            var data = res.data || [];
            var TreeData = [];
            TreeData.push(data);
            _this.toDataFun(TreeData);
            _this.TreeData = TreeData;
          } else {
            _this.$Message.error('查询人员信息失败!');
          }
        }
      },
      // 处理树信息
      toDataFun: function (arr) {
        var _this = this;
        arr.forEach(function (e) {
          e.title = e.name;
          e.expand = true;//展开
          if (e.type) {
            e.type = 'dep';
            var checked_dep_arr = _this.checked_dep_arr;
            if (Utils.idInArray(e.id, checked_dep_arr)) {
              e.checked = true;// 选中
            }
          } else {
            e.type = 'user';
            var checked_users_arr = _this.checked_users_arr;
            if (Utils.idInArray(e.id, checked_users_arr)) {
              e.checked = true;// 选中
            }
          }
          var staff = e.staff || [];
          var children = e.children || [];
          if (children.length == 0) {
            e.children = [];
          }
          e.children.push(...staff);
          _this.toDataFun(e.children);
        });
      },
      // 列表多选 选中数据
      selectionChange: function (selection) {
        var _this = this;
        _this.selectionArr = selection;
      },
      // 隐藏编辑页面
      hideAddModal: function () {
        var _this = this;
        var title = _this.addData.title;
        var content = _this.editor ? _this.editor.getData() : '';
        if (title == '' && (content == '' || content == '<p>&nbsp;</p>')) {
          _this.addCurrentTableData = false;
        } else {
          Modal.confirm(_this, {content: '取消编辑内容将丢失，请确认？'}, function () {
            _this.addCurrentTableData = false;
            if (_this.editor) {
              _this.editor.setData('');
            }
          }, function () {
          });
        }
      },
      // 显示添加界面
      add: function () {
        var _this = this;
        _this.getTreeData();
        _this.ajaxType = 'add';
        _this.addData.title = '';
        _this.addData.type = '';
        _this.addData.tag = '';
        _this.addData.DatePickerValue = [];
        _this.addData.is_notify = false;
        _this.addData.is_workflow = false;
        _this.addData.content = '';
        _this.TreeData = [];
        _this.checked_users_arr = [];
        _this.addCurrentTableData = true;
        if (!_this.editor) {
          _this.initCkeditor();
        } else {
          _this.editor.setData('');
        }
      },
      // 保存数据
      save: function () {
        var _this = this;
        var title = _this.addData.title;
        var type_id = _this.addData.type;
        var tag = _this.addData.tag;
        var approvers = _this.addData.approvers;
        var is_notify = _this.addData.is_notify;
        var is_workflow = _this.addData.is_workflow;
        var DatePickerValue = _this.addData.DatePickerValue;
//        var content = _this.addData.content;
        var content = _this.editor ? _this.editor.getData() : '';
        var CheckedNodes = _this.$refs.user_tree.getCheckedNodes();
        if (!(title && title != '')) {
          _this.$Message.error('请输入标题!');
          return false;
        }
        if (!(type_id && type_id != '')) {
          _this.$Message.error('请选择类别!');
          return false;
        }
        if (CheckedNodes.length == 0) {
          _this.$Message.error('请选择可见范围!');
          return false;
        }
        if (!(approvers && approvers != '')) {
          _this.$Message.error('请选择审批人!');
          return false;
        }
        if (is_workflow == true && DatePickerValue.length < 2) {
          _this.$Message.error('请选择日期!');
          return false;
        }
        if (content == '') {
          _this.$Message.error('请输入内容!');
          return false;
        }
        var startDate = '';
        var endDate = '';
        if (is_workflow == true) {
          var startDateVal = _this.addData.DatePickerValue[0];
          var endDateVal = _this.addData.DatePickerValue[1];
          startDate = Utils.dateToDate(startDateVal);
          endDate = Utils.dateToDate(endDateVal);
        }
        var departments = [];
        var users = [];
        for (var k in CheckedNodes) {
          if (!CheckedNodes[k]) {
            continue;
          }
          var id = CheckedNodes[k].id;
          var type = CheckedNodes[k].type;
          if (type == 'dep') {
            departments.push(id);
          } else if (type == 'user') {
            users.push(id);
          }
        }
        departments = Utils.onlyArray(departments);
        users = Utils.onlyArray(users);
        var data = {
          id: _this.id,
          uid: Util.toJson(localStorage.getItem('userInfo')).id,
          title: title,
          tag: tag,
          tid: type_id,
          content: content,
          range: {
            departments: departments,
            users: users
          },
          is_workflow: is_workflow,
          is_notify: is_notify,
          calendar: {
            start: startDate,
            end: endDate
          },
          approvers: [approvers]
        };
        var url = '/announcement/add';
        if (_this.ajaxType == 'update') {
          url = '/announcement/update';
        }
        var params = {
          url: url,
          type: Util.method.post,
          data: data,
          success: _successFun
        };
        Util.ajax(_this, params);
        _this.saveLoading = true;
        function _successFun(res) {
          _this.saveLoading = false;
          if (res.result == 0) {
            _this.page = 1;
            _this.getData();
            _this.addData.title = '';
            _this.addData.type = '';
            _this.addData.tag = '';
            _this.addData.DatePickerValue = [];
            _this.addData.is_notify = false;
            _this.addData.is_workflow = false;
            _this.addData.content = '';
            if (_this.editor) {
              _this.editor.setData('');
            }
            _this.TreeData = [];
            _this.checked_users_arr = [];

            _this.addCurrentTableData = false;
          } else {
            _this.$Message.error('保存信息失败!');
          }
        }
      },
      // 显示修改界面
      update: function (data, index) {
        var _this = this;
        _this.ajaxType = 'update';
        var id = data.id;
        _this.id = id;
        var data = {
          id: _this.id,
        };
        var params = {
          url: '/announcement/query',
          type: Util.method.get,
          data: data,
          success: _successFun
        };
        Util.ajax(_this, params);
        function _successFun(res) {
          if (res.result == 0) {
            var _data = res.data || [];
            var checked_users_arr = [];
            var departments = [];
            var dep = _data.assign_users.departments;
            if (dep instanceof Array) {
              departments = dep;
            } else {
              departments.push(dep);
            }
            var users = _data.assign_users.users;
            for (var k in departments) {
              if (!departments[k]) {
                continue;
              }
              checked_users_arr.push(departments[k]);
            }
            for (var k in users) {
              if (!users[k]) {
                continue;
              }
              checked_users_arr.push(users[k]);
            }
            var approvers = '';
            var approversArr = _data.approvers || [];
            if (approversArr.length > 0) {
              approvers = approversArr[0].id;
            }

            _this.checked_users_arr = checked_users_arr;
            _this.addData.title = _data.title;
            _this.addData.tag = _data.tag;
            _this.addData.type = _data.type.id;
            _this.addData.DatePickerValue = [];
            _this.addData.is_notify = _data.is_notify;
            _this.addData.is_workflow = _data.is_workflow;
            _this.addData.content = _data.content;
            _this.addData.approvers = approvers;

            _this.getTreeData();
            _this.addCurrentTableData = true;
            if (!_this.editor) {
              _this.initCkeditor();
            } else {
              _this.editor.setData(_this.addData.content);
            }
          } else {
            _this.$Message.error('查询信息失败!');
          }
        }
      },
      // 发布
      fabu: function () {
        var _this = this;
        var data = {
          uid: Util.toJson(localStorage.getItem('userInfo')).id,
          type: 'status',
          id: _this.id,
          status: 5 // 已发布
        };
        var params = {
          url: '/announcement/update',
          type: Util.method.get,
          data: data,
          success: _successFun
        };
        Util.ajax(_this, params);
        _this.saveLoading = true;
        function _successFun(res) {
          _this.saveLoading = false;
          if (res.result == 0) {
            _this.getData();
            _this.showCurrentTableData = false;
          } else {
            _this.$Message.error('发布失败!');
          }
        }
      },
      // 删除
      remove: function () {
        var _this = this;
        var selectionArr = _this.selectionArr;
        if (selectionArr.length == 0) {
          _this.$Message.error('请填选择要删除的数据!');
          return false;
        }
        var selectionIds = [];
        for (var k in selectionArr) {
          if (!selectionArr[k]) {
            continue;
          }
          var id = selectionArr[k].id;
          selectionIds.push(id);
        }
        Modal.confirm(_this, {content: '确定删除选中的信息？'}, function () {
          var data = {
            id: selectionIds,
          };
          var params = {
            url: '/announcement/deleteMultiple',
            type: Util.method.get,
            data: data,
            success: _successFun
          };
          Util.ajax(_this, params);
          function _successFun(res) {
            if (res.result == 0) {
              _this.page = 1;
              _this.getData();
            } else {
              _this.$Message.error('删除信息失败!');
            }
          }
        }, function () {
        });
      },
      // 导出
      ExportData: function () {
        var _this = this;
        var fields = [
          {
            field: 'id',
            title: '#',
            type: 'int',
            order: 1,
          },
          {
            field: 'title',
            title: '标题',
            type: 'varchar',
            order: 2,
          },
          {
            field: 'tag',
            title: '标签',
            type: 'varchar',
            order: 3,
          },
          {
            field: 'create_time',
            title: '创建时间',
            type: 'datetime',
            order: 4,
          },
          {
            field: 'department_name',
            title: '部门',
            type: 'varchar',
            order: 5,
          },
          {
            field: 'status',
            title: '状态',
            type: 'varchar',
            order: 6,
          },
          {
            field: 'content',
            title: '内容',
            type: 'varchar',
            order: 7,
          },
        ];
        var fieldsStr = Util.toStr(fields);
        var data = {
          uid: Util.toJson(localStorage.getItem('userInfo')).id,
          type: 'announcement',
          fields: fieldsStr,
        };
        var params = {
          url: '/file/db2excle',
          type: Util.method.post,
          data: data,
          success: _successFun
        };
        Util.ajax(_this, params);
        function _successFun(res) {
          if (res.result == 0) {
            var url = res.data;
            var date = Utils.dateToDateString(new Date());
            Utils.DownloadFile(url, '导出公告_' + date + '.xlsx');
          } else {
            _this.$Message.error('导出信息失败!');
          }
        }
      },
    }
  };
</script>
